package com.fitz.registry;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.fitz.loadbalance.AbstractLoadBalance;
import com.fitz.loadbalance.RandomLoadBalance;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author gousl01
 * @date 2021/5/1 17:32
 * @desc
 */
@Slf4j
public class DefaultRegistry {

    public static final String SERVER_ADDR = "serverAddr";

    /**
     * key  interfaceName
     * value  服务列表
     */
    public ConcurrentHashMap<String,List<InstanceInfo>> serviceInfoMap = new ConcurrentHashMap<>();

    public DefaultRegistry() {
    }

    public InstanceInfo discover(InstanceRegistry instanceRegistry,Class<? extends AbstractLoadBalance> loadBalanceClass,String serviceName) {
        AbstractLoadBalance loadBalance = null;
        try {
            loadBalance = loadBalanceClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        List<InstanceInfo> list = serviceInfoMap.get(serviceName);
        if (CollectionUtils.isEmpty(list)){
            list = instanceRegistry.getAllInstances(serviceName);
            serviceInfoMap.put(serviceName,list);
        }
        InstanceInfo instanceInfo = null;
        int size = list.size();
        if (size > 0) {
            if (size == 1) {
                instanceInfo = list.get(0);
                log.debug("using only data: {}", instanceInfo.getServiceName());
            } else {
                if (loadBalance == null){
                    loadBalance = new RandomLoadBalance();
                }
                instanceInfo = loadBalance.loadBalance(list);
            }
        }
        return instanceInfo;
    }

    public InstanceInfo discover(Class<? extends AbstractLoadBalance> loadBalanceClass, List<InstanceInfo> instances) {
        AbstractLoadBalance loadBalance = null;
        try {
            loadBalance = loadBalanceClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        InstanceInfo instanceInfo = null;
        int size = instances.size();
        if (size > 0) {
            if (size == 1) {
                instanceInfo = instances.get(0);
                log.debug("using only data: {}", instanceInfo.getServiceName());
            } else {
                if (loadBalance == null){
                    loadBalance = new RandomLoadBalance();
                }
                instanceInfo = loadBalance.loadBalance(instances);
            }
        }
        return instanceInfo;
    }
}
